using System.Text.Json.Serialization;
using Vin.Extension.Win32.Command.Node;

namespace Vin.Extension.Win32.Command.Workflow;

public class WorkflowData : IJsonOnDeserialized
{
    /// <summary>
    /// 工作流Id
    /// </summary>
    public string Id { get; set; } = Guid.NewGuid().ToString();

    /// <summary>
    /// 开始节点Id
    /// </summary>
    public string StartNodeId { get; set; } = null!;

    public NodeGroup StartNodeGroup => NodeGroupList.FirstOrDefault(x => x.Id == StartNodeId)!;

    /// <summary>
    /// 所有的节点数据
    /// </summary>
    public List<NodeData> NodeDataList { get; set; } = new();

    /// <summary>
    /// 输入节点
    /// </summary>
    public List<NodeGroup> NodeGroupList { get; set; } = new();

    /// <summary>
    /// 根据节点Id获取节点数据
    /// </summary>
    public NodeGroup? GetNodeGroup(string nodeId) => NodeGroupList.FirstOrDefault(x => x.Id == nodeId);

    #region 变量

    /// <summary>
    /// 变量字典
    /// </summary>
    public Dictionary<string, Variable> VariableDict { get; internal set; } = new();

    #region 变量操作

    public Variable? GetVariable(string key) => VariableDict.ContainsKey(key) ? VariableDict[key] : null;
    public object? GetVariableValue(string key) => GetVariable(key)?.GetValue();

    public bool SetVariableValue(string key, object value)
    {
        if (VariableDict.ContainsKey(key))
        {
            VariableDict[key].SetValue(value);
            return true;
        }

        return false;
    }

    #endregion

    #region 全局变量操作

    public object? GetResultValue => GetVariableValue(GlobalVariables.Result);

    public bool SetResultValue(string text) => SetVariableValue(GlobalVariables.Result, text);

    #endregion

    #endregion

    public void OnDeserialized()
    {
        InitGlobalVariable();
    }

    private void InitGlobalVariable()
    {
        VariableDict.Add(GlobalVariables.ClipboardText, new Variable()
        {
            Key = "ClipboardText",
            Type = VariableType.Dynamic,
            Remark = "剪贴板文本",
            DynamicValue = () => { return Clipboard.GetText(); }
        });
        VariableDict.Add(GlobalVariables.Result, new Variable()
        {
            Key = "Result",
            Type = VariableType.Dynamic,
            Remark = "上个节点输出结果",
        });
    }
}